<template>
  <div class="login-page">
    <!-- 背景装饰 -->
    <div class="login-page__background">
      <div class="login-page__background-shapes"></div>
    </div>

    <!-- 主登录卡片 -->
    <div class="login-page__container">
      <div class="login-page__card">
        <!-- 头部Logo和标题 -->
        <div class="login-page__header">
          <div class="login-page__logo">
            <div class="logo-icon">
              <i class="fas fa-utensils"></i>
            </div>
            <h1 class="logo-text">COKFOOD</h1>
          </div>
          <p class="login-page__subtitle">管理后台系统</p>
        </div>

        <!-- 登录表单 -->
        <div class="login-page__form-container">
          <div class="login-page__form-header">
            <h2>用户登录</h2>
            <p>请输入您的账户信息进行登录</p>
          </div>

          <form class="login-page__form">
            <div class="form-group">
              <label class="form-label">
                <i class="fas fa-user"></i>
                用户名
              </label>
              <div class="input-wrapper">
                <input
                  v-model="loginForm.phone"
                  type="text"
                  class="form-input"
                  placeholder="请输入用户名"
                  required
                >
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">
                <i class="fas fa-lock"></i>
                密码
              </label>
              <div class="input-wrapper">
                <input
                  v-model="loginForm.pwd"
                  type="password"
                  class="form-input"
                  placeholder="请输入密码"
                  required
                >
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">
                <i class="fas fa-user-tag"></i>
                用户角色
              </label>
              <div class="select-wrapper">
                <select v-model="role" class="form-select" required>
                  <option value="agent">区域代理</option>
                  <option value="distributor">业务员</option>
                  <option value="admin">管理员</option>
                </select>
                <i class="fas fa-chevron-down select-arrow"></i>
              </div>
            </div>

            <button
              type="button"
              @click="handleLogin"
              class="login-btn"
            >
              <i class="fas fa-sign-in-alt"></i>
              立即登录
            </button>
          </form>

          <!-- 当前用户信息 -->
          <div v-if="currentUser" class="user-info-card">
            <div class="user-info-header">
              <i class="fas fa-check-circle"></i>
              <h3>登录成功</h3>
            </div>
            <div class="user-info-content">
              <div class="user-info-item">
                <span class="label">用户名:</span>
                <span class="value">{{ currentUser.name }}</span>
              </div>
              <div class="user-info-item">
                <span class="label">角色:</span>
                <span class="value">{{ currentUser.role }}</span>
              </div>
            </div>
            <button @click="handleLogout" class="logout-btn">
              <i class="fas fa-sign-out-alt"></i>
              退出登录
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 页脚 -->
    <div class="login-page__footer">
      <p>&copy; {{ new Date().getFullYear() }} COKFOOD. All rights reserved.</p>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { useUserStore } from '@/stores/modules/user'
  import { showToast } from 'vant'
  import { login, loginAdmin } from '@/api/index'

  const router = useRouter()
  const userStore = useUserStore()

  const username = ref('')
  const role = ref('agent') // 默认选择经销商角色

  const currentUser = computed(() => userStore.currentUser)

  const loginForm = ref({
    phone: '',
    pwd: '',
    captcha: ''
  })

  const resetLoginForm = () => {
    loginForm.value = {
      phone: '',
      pwd: '',
      captcha: ''
    }
  }

  // 登录功能 => 经销商,代理商
  const loginRequest1 = async () => {
    try {
      const res = await login(loginForm.value)

      const token = res.data.token
      userStore.setToken(token)

      // 创建并设置用户对象 - 这是关键修复
      const mockUser = {
        id: 'test-' + Date.now(),
        name: loginForm.value.phone, // 使用手机号作为用户名
        email: `${loginForm.value.phone}@example.com`,
        role: role.value as 'admin' | 'user' | 'agent' | 'distributor',
        // avatar: 'https://randomuser.me/api/portraits/men/1.jpg'
        avatar: ''
      }
      // 设置用户信息 - 修复isLoggedIn问题
      userStore.setUser(mockUser)

      // await new Promise(resolve => setTimeout(resolve, 2000));

      if (role.value == 'agent') {
        router.push('/agent') // 修复：添加/，使用redirect路径
      }

      if(role.value == 'distributor') {
        router.push('/distributor') // 修复：添加/，使用redirect路径
      }

    } catch(err) {
      console.log(7777,err)
    }
  }

  const loginAdminRequest = async () => {
    try {
      let data = JSON.parse(JSON.stringify(loginForm.value))

      data.username = data.phone

      const res = await loginAdmin(data)

      const token = res.data.token

      // 创建模拟用户对象
      const mockUser = {
        id: 'test-' + Date.now(),
        name: username.value,
        email: `${username.value}@example.com`,
        role: role.value as 'admin' | 'user' | 'agent' | 'distributor',
        avatar: 'https://randomuser.me/api/portraits/men/1.jpg'
      }

      userStore.setUser(mockUser)

      userStore.setToken(token)

      router.push('/admin/dashboard')
    } catch(error) {

    }
  }

  // 模拟登录
  const handleLogin = () => {
    if (!loginForm.value.phone) {
      showToast('请输入用户名')
      return
    }

    if(role.value == 'distributor' || role.value == 'agent') {
      loginRequest1()
    }

    if(role.value === 'admin') {
      loginAdminRequest()
    }

    // console.log(789789,loginForm)

    return

    // 创建模拟用户对象
    const mockUser = {
      id: 'test-' + Date.now(),
      name: username.value,
      email: `${username.value}@example.com`,
      role: role.value as 'admin' | 'user' | 'agent' | 'distributor',
      avatar: 'https://randomuser.me/api/portraits/men/1.jpg'
    }

    // 模拟token
    const mockToken = 'test-token-' + Date.now()

    // 设置用户和token
    userStore.setUser(mockUser)
    userStore.setToken(mockToken)

    // 保存到localStorage便于持久化
    localStorage.setItem('user', JSON.stringify(mockUser))

    showToast(`已成功以${role.value}角色登录`)

    // 不同角色导航到不同页面
    if (role.value === 'distributor') {
      router.push('/distributor/dashboard')
    } else if (role.value === 'admin') {
      router.push('/admin/dashboard')
    } else {
      router.push('/')
    }
  }

  // 退出登录
  const handleLogout = () => {
    userStore.logout()
    showToast('已退出登录')
    router.push('/login')
  }

  // 页面加载时检查用户状态
  onMounted(() => {
    userStore.checkAuth()
  })
</script>

<style scoped>
  .login-page {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    position: relative;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  .login-page__background {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
    z-index: 0;
  }

  .login-page__background-shapes::before,
  .login-page__background-shapes::after {
    content: '';
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
  }

  .login-page__background-shapes::before {
    width: 300px;
    height: 300px;
    top: -150px;
    right: -150px;
    animation: float 6s ease-in-out infinite;
  }

  .login-page__background-shapes::after {
    width: 200px;
    height: 200px;
    bottom: -100px;
    left: -100px;
    animation: float 8s ease-in-out infinite reverse;
  }

  @keyframes float {
    0%, 100% { transform: translateY(0px) rotate(0deg); }
    50% { transform: translateY(-20px) rotate(10deg); }
  }

  .login-page__container {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    position: relative;
    z-index: 1;
  }

  .login-page__card {
    background: white;
    border-radius: 20px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    width: 100%;
    max-width: 450px;
    animation: slideUp 0.6s ease-out;
  }

  @keyframes slideUp {
    from {
      opacity: 0;
      transform: translateY(30px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .login-page__header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 40px 30px;
    text-align: center;
  }

  .login-page__logo {
    margin-bottom: 10px;
  }

  .logo-icon {
    display: inline-block;
    width: 60px;
    height: 60px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 15px;
  }

  .logo-icon i {
    font-size: 24px;
    color: white;
  }

  .logo-text {
    font-size: 28px;
    font-weight: 700;
    margin: 0;
    letter-spacing: 2px;
  }

  .login-page__subtitle {
    margin: 0;
    opacity: 0.9;
    font-size: 16px;
  }

  .login-page__form-container {
    padding: 40px 30px;
  }

  .login-page__form-header {
    text-align: center;
    margin-bottom: 30px;
  }

  .login-page__form-header h2 {
    color: #333;
    font-size: 24px;
    margin: 0 0 8px 0;
    font-weight: 600;
  }

  .login-page__form-header p {
    color: #666;
    margin: 0;
    font-size: 14px;
  }

  .form-group {
    margin-bottom: 25px;
  }

  .form-label {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #374151;
    font-weight: 500;
    font-size: 14px;
    margin-bottom: 8px;
  }

  .form-label i {
    color: #667eea;
    width: 16px;
  }

  .input-wrapper,
  .select-wrapper {
    position: relative;
  }

  .form-input,
  .form-select {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    font-size: 16px;
    transition: all 0.3s ease;
    background: #fafafa;
    box-sizing: border-box;
  }

  .form-input:focus,
  .form-select:focus {
    outline: none;
    border-color: #667eea;
    background: white;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  }

  .select-wrapper {
    position: relative;
  }

  .select-arrow {
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    color: #9ca3af;
    pointer-events: none;
    font-size: 12px;
  }

  .form-select {
    appearance: none;
    cursor: pointer;
    padding-right: 40px;
  }

  .login-btn {
    width: 100%;
    padding: 14px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 12px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }

  .login-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
  }

  .login-btn:active {
    transform: translateY(0);
  }

  .user-info-card {
    margin-top: 30px;
    background: #f8fafc;
    border-radius: 12px;
    padding: 20px;
    border: 1px solid #e2e8f0;
  }

  .user-info-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
  }

  .user-info-header i {
    color: #10b981;
    font-size: 18px;
  }

  .user-info-header h3 {
    color: #1f2937;
    margin: 0;
    font-size: 16px;
    font-weight: 600;
  }

  .user-info-content {
    margin-bottom: 15px;
  }

  .user-info-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
  }

  .user-info-item .label {
    color: #6b7280;
    font-size: 14px;
    width: 60px;
    flex-shrink: 0;
  }

  .user-info-item .value {
    color: #1f2937;
    font-weight: 500;
    font-size: 14px;
  }

  .logout-btn {
    padding: 10px 20px;
    background: #ef4444;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .logout-btn:hover {
    background: #dc2626;
    transform: translateY(-1px);
  }

  .login-page__footer {
    text-align: center;
    padding: 20px;
    color: rgba(255, 255, 255, 0.8);
    font-size: 14px;
    position: relative;
    z-index: 1;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .login-page__container {
      padding: 10px;
    }

    .login-page__card {
      max-width: 100%;
      border-radius: 12px;
    }

    .login-page__header {
      padding: 30px 20px;
    }

    .login-page__form-container {
      padding: 30px 20px;
    }

    .logo-text {
      font-size: 24px;
    }
  }

  @media (max-width: 480px) {
    .form-input,
    .form-select {
      font-size: 16px; /* 防止iOS缩放 */
    }
  }
</style>
